<template>
  <div>
    <Row>
      <Col span="24">
        <Tabs v-model:activeKey="activeKey" @change="tabChange">
          <TabPane :tab="t('routes.components.permissionModal.user')" key="user">
            <BasicTable
              @register="registerTable"
              :rowSelection="{
                type: 'checkbox',
                onChange: handleUserCheck,
              }"
              @row-click="handleRowClick"
            />
          </TabPane>
          <TabPane :tab="t('routes.components.permissionModal.depPart')" key="depart">
            <div style="height: 300px; overflow-y: scroll; overflow-x: hidden">
              <BasicTree
                checkable
                :treeData="departData"
                :toolbar="true"
                :search="true"
                :title="t('routes.components.permissionModal.depPart')"
                v-model:checkedKeys="departSelectedData"
                @check="handleDepartCheck"
                @select="handleDepartSelect"
              />
            </div>
          </TabPane>
          <TabPane :tab="t('routes.components.permissionModal.role')" key="role">
            <div style="height: 300px; overflow-y: scroll; overflow-x: hidden">
              <BasicTree
                checkable
                :treeData="roleData"
                :toolbar="true"
                :search="true"
                :title="t('routes.components.permissionModal.role')"
                v-model:checkedKeys="roleSelectedData"
                @check="handleRoleCheck"
                @select="handleRoleSelect"
              />
            </div>
          </TabPane>
        </Tabs>
      </Col>
    </Row>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { Row, Col, Tabs, TabPane } from 'ant-design-vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicTree } from '/@/components/Tree/index';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { getUserColumns } from './tableData';
  import { Getallpersondto, GetAllOrgTreeDataHaveCompany } from '/@/api/demo/system';
  import {
    GetFolderRoleList,
    ReverseParsePermissions,
    GetFileTypeByUserId,
  } from '/@/api/demo/document';

  // 定义可以触发的事件
  const emit = defineEmits(['sendData', 'sendFileTypeData']);

  // 定义接收的props
  const props = defineProps({
    // eslint-disable-next-line vue/prop-name-casing
    DirectoryData: {
      type: Array,
    }, // 指定数据类型
  });

  const { t } = useI18n();
  const activeKey = ref('user');
  const departData = ref<any>([]);
  const roleData = ref<any>([]);

  // 公司名称
  const companyName = ref<string>('清软英泰');
  // 用户选中数据
  const userSelectedData = ref<any>([]);
  // 部门选中数据
  const departSelectedData = ref<any>([]);
  // 角色选中数据
  const roleSelectedData = ref<any>([]);
  // 用户select数据
  const selectUserData = ref<any>('');
  // 部门select数据
  const selectDepartData = ref<any>('');
  // 角色select数据
  const selectRoleData = ref<any>('');

  // 使用 defineExpose 暴露子组件的数据和方法
  defineExpose({
    activeKey,
    userSelectedData,
    departSelectedData,
    roleSelectedData,
    selectUserData,
    selectDepartData,
    selectRoleData,
  });

  // tab切换
  const tabChange = (key: string) => {
    // 如果key为1，则清空部门和角色的选中状态，如果key为2，则清空用户和角色的选中状态，如果key为3，则清空用户和部门的选中状态
    if (key === 'user') {
      departSelectedData.value = [];
      roleSelectedData.value = [];
      selectDepartData.value = '';
      selectRoleData.value = '';
    } else if (key === 'depart') {
      clearSelectedRowKeys();
      roleSelectedData.value = [];
      selectUserData.value = '';
      selectRoleData.value = '';
    } else if (key === 'role') {
      clearSelectedRowKeys();
      departSelectedData.value = [];
      selectUserData.value = '';
      selectDepartData.value = '';
    }
  };

  // 处理行点击事件
  const handleRowClick = async (record: any) => {
    selectUserData.value = record.id;
    if (props.DirectoryData != null) {
      const viewUserPermissionData = await ReverseParsePermissions(
        selectUserData.value,
        props.DirectoryData.toString(),
      );
      emit('sendData', viewUserPermissionData);
    }
    // 用户查找文件类型
    const fileTypeData = await GetFileTypeByUserId(record.id);
    emit('sendFileTypeData', fileTypeData);
  };

  // 部门点击事件
  const handleDepartSelect = async (selectedKeys: any) => {
    selectDepartData.value = selectedKeys;
    // 判断层级独立还是层级关联
    const departResult =
      selectDepartData.value.hasOwnProperty('checked') && selectDepartData.value.checked.length > 0
        ? selectDepartData.value.checked
        : selectDepartData.value;
    if (props.DirectoryData != null) {
      const viewUserPermissionData = await ReverseParsePermissions(
        departResult,
        props.DirectoryData.toString(),
      );
      emit('sendData', viewUserPermissionData);
    }
    // 用户查找文件类型
    const fileTypeData = await GetFileTypeByUserId(departResult);
    emit('sendFileTypeData', fileTypeData);
  };

  // 角色点击事件
  const handleRoleSelect = async (selectedKeys: any) => {
    selectRoleData.value = selectedKeys;
    // 判断层级独立还是层级关联
    const roleResult =
      selectRoleData.value.hasOwnProperty('checked') && selectRoleData.value.checked.length > 0
        ? selectRoleData.value.checked
        : selectRoleData.value;
    if (props.DirectoryData != null) {
      const viewUserPermissionData = await ReverseParsePermissions(
        roleResult,
        props.DirectoryData.toString(),
      );
      emit('sendData', viewUserPermissionData);
    }
    // 用户查找文件类型
    const fileTypeData = await GetFileTypeByUserId(roleResult);
    emit('sendFileTypeData', fileTypeData);
  };

  // 用户选中事件
  const handleUserCheck = async (checkedKeys: any) => {
    userSelectedData.value = checkedKeys;
  };

  // 部门选中事件
  const handleDepartCheck = (checkedKeys: any) => {
    departSelectedData.value = checkedKeys;
  };

  // 角色选中事件
  const handleRoleCheck = (checkedKeys: any) => {
    roleSelectedData.value = checkedKeys;
  };

  // 获取部门数据
  GetAllOrgTreeDataHaveCompany(companyName.value).then((res) => {
    departData.value = res.map((item) => {
      return {
        ...item,
        title: item.title,
        key: item.orgId,
        children: item.childrenOrg.map((child) => {
          return {
            ...child,
            title: child.title,
            key: child.orgId,
          };
        }),
      };
    });
  });

  // 获取角色数据
  GetFolderRoleList().then((res) => {
    roleData.value = res;
  });

  // 用户表格初始化
  const [registerTable, { clearSelectedRowKeys }] = useTable({
    api: Getallpersondto,
    rowKey: 'id',
    columns: getUserColumns(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: false, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    canResize: false,
    pagination: false,
    maxHeight: 300,
  });
</script>

<style scoped></style>
